import {Component} from '@angular/core';
import {Hero} from "../hero";
import {NgForOf, NgIf, UpperCasePipe} from "@angular/common";
import {FormsModule} from "@angular/forms";
import {HeroDetailComponent} from "../hero-detail/hero-detail.component";
import {HeroService} from "../hero.service";
import {RouterLink} from "@angular/router";

@Component({
  selector: 'app-heroes',
  imports: [
    UpperCasePipe,
    FormsModule,
    NgForOf,
    NgIf,
    HeroDetailComponent,
    RouterLink,
  ],
  templateUrl: './heroes.component.html',
  standalone: true,
  styleUrl: './heroes.component.css'
})
export class HeroesComponent {
  selectedHero?: Hero;
  heroes: Hero[] = [];


  //生命周期---钩子函数
  ngOnInit(): void {
    this.getHeroes();
  }


  onSelect(hero: Hero) {
    if (this.selectedHero === hero) {
      this.selectedHero = undefined;
    } else {
      this.selectedHero = hero;
    }
  }

  getHeroes(): void {
    //同步
    //this.heroes = this.heroService.getHeroes();
    //异步获取
    this.heroService.getHeroes().subscribe(heroes => this.heroes = heroes)
  }

  //使用构造方法注入HeroService
  constructor(private heroService: HeroService) {
  }
}
